package com.youmans.dfsservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youmans.common_utils.config.Result;
import com.youmans.common_utils.handler.JwtUtils;
import com.youmans.common_utils.vo.UserForPic;
import com.youmans.common_utils.vo.pictureQuery;
import com.youmans.dfsservice.client.UserInfoFeignClient;
import com.youmans.dfsservice.entity.YoumansPicture;
import com.youmans.dfsservice.service.YoumansPictureService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.UUID;

/**
 * <p>
 * 图片表 前端控制器
 * </p>
 *
 * @author youmans
 * @since 2022-10-16
 */
@RestController
@RequestMapping("/dfsservice/picture")
public class YoumansPictureController {
    @Autowired
    private YoumansPictureService youmansPictureService ;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient ;

    @GetMapping("findAllByUserId")
    public Result findAllByUserId(HttpServletRequest request){
        List<YoumansPicture> list =  youmansPictureService.findAllByUserId(request);
        return Result.ok(list).message("查询数据成功");
    }

    @GetMapping("findAll")
    public Result findAll(){
        List<YoumansPicture> list =  youmansPictureService.findAll();
        return Result.ok(list).message("查询数据成功");
    }

    //TODO    批量保存,目前未完善
    @PostMapping("batch-save")
    public Result batchSave(@RequestBody List<YoumansPicture> youmansPicture){
        for (YoumansPicture picture : youmansPicture) {
            UUID uuid = UUID.randomUUID();
            String pid = picture.getPid();
            String pid2 = pid.substring(0,8)+uuid.toString().replaceAll("[a-zA-Z]+","").replaceAll("-","").substring(0,5);
            picture.setPid(pid2);
        }
        boolean save = youmansPictureService.saveBatch(youmansPicture);
        return save?Result.ok():Result.fail();
    }

    @PostMapping("save")
    @CacheEvict(value = "userPics",allEntries = true)
    public Result save(@RequestBody YoumansPicture youmansPicture){
        boolean save = youmansPictureService.save(youmansPicture);
        return save?Result.ok():Result.fail();
    }

    @DeleteMapping("remove/{id}")
    @CacheEvict(value = "userPics",allEntries = true)
    public Result remove(@PathVariable String id){
//        youmansPictureService.removeById(id)错误代码;
        LambdaQueryWrapper<YoumansPicture> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YoumansPicture::getPid,id) ;
        youmansPictureService.remove(queryWrapper);
        return Result.ok();
    }

    @PostMapping("get/{id}")
    public Result getById(@PathVariable String id){
        YoumansPicture picture = youmansPictureService.getById(id);
        System.out.println(picture);
        return Result.ok(picture);
    }

    @PostMapping("update")
    public Result<Object> update(@RequestBody YoumansPicture youmansPicture){
        youmansPictureService.updateById(youmansPicture);
        return Result.ok(null);
    }
//    @PostMapping("update2/{id}")
//    public boolean update2(@PathVariable int id){
//        YoumansPicture picture = youmansPictureService.getById(id);
//        picture.setNewFilename("picture");
//        return youmansPictureService.updateById(picture);
//    }
    @CacheEvict(value = "userPics",allEntries = true)
    @ApiOperation(value = "根据id列表删除")
    @DeleteMapping("batch-remove")
    public Result batchRemove(@RequestBody List<String> idList) {
        LambdaQueryWrapper<YoumansPicture> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(YoumansPicture::getPid,idList);
        youmansPictureService.remove(queryWrapper);
        return Result.ok(null);
    }


    @ApiOperation(value = "根据id列表恢复")
    @PostMapping("batchDelBack")
    public Result batchDelBack(@RequestBody List<String> idList) {
        youmansPictureService.batchDelBack(idList);
        return Result.ok(null);
    }

    //条件查询分页列表
//    @CacheEvict
    @ApiOperation(value = "获取分页列表")
    @PostMapping("{page}/{limit}")
    @Cacheable(value = "allpics",key = "#pictureQuery.username+" +"'-'+#page")
    public Result index(
            @ApiParam(name = "page", value = "当前页码", required = true)
            @PathVariable Long page,
            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable Long limit,
            @ApiParam(name = "teacherVo", value = "查询对象", required = false)
            @RequestBody(required = false) pictureQuery pictureQuery) {
        IPage<YoumansPicture> pageModel ;
        //创建page对象，传递当前页和每页记录数
        Page<YoumansPicture> pageParam = new Page<>(page, limit);
        //封装条件
        QueryWrapper<YoumansPicture> wrapper = new QueryWrapper<>();
        //获取条件值
        if(!StringUtils.isEmpty(pictureQuery)){
            String name = pictureQuery.getUsername();//名称
            String oriName = pictureQuery.getOriginalFilename();//状态
            String begin = pictureQuery.getBegin();
            String end = pictureQuery.getEnd();
            if(!StringUtils.isEmpty(name)) {
//                int userIdByname = userInfoFeignClient.getUserIdByname(name);
                String set = userInfoFeignClient.getUserIdByname(name);
//                set.add(9527);
                wrapper.eq("user_id",set);
//                wrapper.eq("user_id",set);
            }

//            if(!StringUtils.isEmpty(oriName)) {
//                wrapper.like("original_filename",oriName);
//            }
            if(!StringUtils.isEmpty(begin)) {
                wrapper.ge("gmt_create",begin);
            }
            if(!StringUtils.isEmpty(end)) {
                wrapper.le("gmt_create",end);
            }
            wrapper.orderByDesc("gmt_create");

        }
        List<UserForPic> forPicList = userInfoFeignClient.findAll();

        //调用方法得到分页查询结果
        pageModel = youmansPictureService.page(pageParam, wrapper);

        setUsernameById(pageModel, forPicList);
        return Result.ok(pageModel);
    }



    //条件查询分页列表ByUserId
    @ApiOperation(value = "获取分页列表")
    @PostMapping("listByUserId/{page}/{limit}")
    @Cacheable(value = "userPics",key = "#pictureQuery.username+" +"'-'+#page")
    public Result indexByUserId(
            @ApiParam(name = "page", value = "当前页码", required = true)
            @PathVariable Long page,
            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable Long limit,
            @ApiParam(name = "teacherVo", value = "查询对象", required = false)
            @RequestBody(required = false) pictureQuery pictureQuery,
            HttpServletRequest request) {

        //创建page对象，传递当前页和每页记录数
        Page<YoumansPicture> pageParam = new Page<>(page, limit);
        //封装条件
        QueryWrapper<YoumansPicture> wrapper = new QueryWrapper<>();
        //获取条件值
        if(!StringUtils.isEmpty(pictureQuery)){
            String name = pictureQuery.getUsername();//名称
            String oriName = pictureQuery.getOriginalFilename();//状态
            String begin = pictureQuery.getBegin();
            String end = pictureQuery.getEnd();
            String id = JwtUtils.getMemberIdByJwtToken(request);
//            if(!StringUtils.isEmpty(name)) {
//                wrapper.in("user_id",set);
            wrapper.eq("user_id",id);
//            }

            if(!StringUtils.isEmpty(oriName)) {
                wrapper.like("original_filename",oriName);
            }
            if(!StringUtils.isEmpty(begin)) {
                wrapper.ge("gmt_create",begin);
            }
            if(!StringUtils.isEmpty(end)) {
                wrapper.le("gmt_create",end);
            }
            wrapper.orderByDesc("gmt_create");//时间最近->以前的

        }
        List<UserForPic> forPicList = userInfoFeignClient.findAll();

        //调用方法得到分页查询结果
        IPage<YoumansPicture> pageModel  = youmansPictureService.page(pageParam, wrapper);

        setUsernameById(pageModel, forPicList);
        return Result.ok(pageModel);
    }


    //根据用户id设置用户名
    private void setUsernameById(IPage<YoumansPicture> pageModel, List<UserForPic> forPicList) {
        pageModel.getRecords().forEach((item)->{
            for (UserForPic userForPic : forPicList) {
                if(item.getUserId().equals(userForPic.getUserId())){
                    item.setUsername(userForPic.getUsername());
                }
            }
            // System.out.println(forPicList);
        });
    }

    //条件查询分页列表
    @ApiOperation(value = "获取分页列表")
    @PostMapping("picture-back")
//    @Cacheable(value = "deletePics",key = "#pictureQuery.username+" +"'-'+#page")
    public Result indexByBack(
            @ApiParam(name = "teacherVo", value = "查询对象", required = false)
            @RequestBody(required = false) pictureQuery pictureQuery) {
        IPage<YoumansPicture> pageModel;
        String user_id =null;
        String gmt_create = pictureQuery.getBegin();
        if(!StringUtils.isEmpty(pictureQuery)){
            String name = pictureQuery.getUsername();//名称
            if(!StringUtils.isEmpty(name)){
                user_id = userInfoFeignClient.getIdByname(name);
            }
        }
        pageModel = youmansPictureService.selectDelPic(gmt_create,user_id);

        List<UserForPic> forPicList = userInfoFeignClient.findAll();
        setUsernameById(pageModel, forPicList);

        return Result.ok(pageModel);
    }

}

